﻿using IService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Model.Models;
using ModelDto;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AssetManegement.Filter
{
    /// <summary>
    /// 自定义系统异常
    /// </summary>
    public class MyExceptionFilterAttribute : ExceptionFilterAttribute
    {

        private readonly ILogger<MyExceptionFilterAttribute> _logger;
        private readonly ILogService _logService;

        /// <summary>
        /// 构造
        /// </summary>
        public MyExceptionFilterAttribute(ILogger<MyExceptionFilterAttribute> logger, ILogService logService)
        {
            _logger = logger;
            _logService = logService;
        }

        /// <summary>
        /// 异常发生
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {

            if (!context.ExceptionHandled)
            {
                //异常未处理
                _logger.LogError($"接口：{context.HttpContext.Request.Path} 错误描述：{context.Exception.Message}  错误日志：{context.Exception.StackTrace}");


                try
                {
                    Account account = new Account();

                    try
                    {
                        string tempUser = context.HttpContext.Request.Headers["LUserInfo"].ToString();
                        AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

                        if (CurrentUser != null && CurrentUser.Account != null)
                        {
                            account = CurrentUser.Account;
                        }
                    }
                    catch (Exception e)
                    {

                    }
                   
                    _logService.WriteErrorLog(account, context.HttpContext.Request.Path, context.Exception.Message, context.Exception.StackTrace);
                }
                catch (Exception e)
                {

                }
               

                context.Result = new JsonResult(new JsonResultL().SysFail());

                context.ExceptionHandled = true;
            }

            //base.OnException(context);
        }
    }
}
